﻿import { Component, Injector, ViewChild } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { EstimatedCostServiceProxy } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'realtimeCostDetailModal',
    templateUrl: './realtime-cost-detail-modal.component.html'
})
export class RealtimeCostDetailModalComponent extends AppComponentBase {
    @ViewChild('modal') modal: ModalDirective;
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;

    isShown = false;
    isInitialized = false;
    batchId = '';
    date = new Date();

    constructor(injector: Injector, public _costService: EstimatedCostServiceProxy) {
        super(injector);
    }

    show(batchId: string, date: Date): void {
        this.batchId = batchId;
        this.date = date;
        this.modal.show();
    }

    shown(): void {
        this.isShown = true;
        this.getRecordsIfNeeds(null);
    }

    getRecordsIfNeeds(event?: LazyLoadEvent): void {
        if (!this.isShown) {
            return;
        }

        if (!this.batchId && !this.isInitialized) {
            return;
        }

        this.getDetailCosts(event);
        this.isInitialized = true;
    }

    getDetailCosts(event?: LazyLoadEvent): void {
        if (!this.isShown) {
            return;
        }

        this.primengTableHelper.showLoadingIndicator();
        this._costService
            .getEstimatedCosts(
                this.batchId,
                this.date ? this.date.getFullYear() : undefined,
                this.date ? this.date.getMonth() + 1 : undefined,
                undefined,
                undefined,
                undefined,
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
            .subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
            });
    }

    close(): void {
        this.modal.hide();
    }
}
